import { resolve } from 'path'
import { loadEnv } from 'vite'
import type { UserConfig, ConfigEnv } from 'vite'
import Vue from '@vitejs/plugin-vue'
import VueJsx from '@vitejs/plugin-vue-jsx'
import progress from 'vite-plugin-progress'
import { ViteEjsPlugin } from 'vite-plugin-ejs'
import { viteMockServe } from 'vite-plugin-mock'
import PurgeIcons from 'vite-plugin-purge-icons'
import ServerUrlCopy from 'vite-plugin-url-copy'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import'
import UnoCSS from 'unocss/vite'
import { visualizer } from 'rollup-plugin-visualizer'
import pxtorem from 'postcss-pxtorem'
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import fs from 'fs-extra'

// https://vitejs.dev/config/
const root = process.cwd()

function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}

// 修改：改进复制函数，复制到更明显的位置
function createCopyJsonFilesPlugin(env: any, isBuild: boolean) {
  return {
    name: 'copy-json-files',
    closeBundle() {
      if (!isBuild) return // 只在构建时运行

      try {
        const sourceDirs = [
          { from: 'src/utils', to: 'config' }, // 复制到 dist/config 目录

        ]

        const targetDir = pathResolve(env.VITE_OUT_DIR || 'dist')
        let totalCopied = 0

        sourceDirs.forEach(({ from, to }) => {
          const sourceDir = pathResolve(from)
          const targetPath = resolve(targetDir, to)

          if (fs.existsSync(sourceDir)) {
            // 确保目标目录存在
            fs.ensureDirSync(targetPath)

            // 读取源目录中的所有文件
            const files = fs.readdirSync(sourceDir)

            files.forEach(file => {
              if (file.endsWith('.json')) {
                const sourceFile = resolve(sourceDir, file)
                const targetFile = resolve(targetPath, file)

                try {
                  fs.copySync(sourceFile, targetFile, { overwrite: true })
                  console.log(`✅ 复制 JSON 文件: ${file} -> ${to}/${file}`)
                  totalCopied++
                } catch (error) {
                  console.error(`❌ 复制失败: ${file}`, error)
                }
              }
            })
          } else {
            console.log(`⚠️  源目录不存在: ${sourceDir}`)
          }
        })

        if (totalCopied > 0) {
          console.log(`🎉 JSON 文件复制完成！共复制 ${totalCopied} 个文件到 dist 目录`)
          console.log(`📁 文件位置:`)
          sourceDirs.forEach(({ to }) => {
            const targetPath = resolve(targetDir, to)
            if (fs.existsSync(targetPath)) {
              const files = fs.readdirSync(targetPath).filter(f => f.endsWith('.json'))
              if (files.length > 0) {
                console.log(`   📂 ${to}/: ${files.join(', ')}`)
              }
            }
          })
        } else {
          console.log('ℹ️  未找到任何 JSON 文件需要复制')
        }

      } catch (error) {
        console.error('❌ 复制 JSON 文件时出错:', error)
      }
    }
  }
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
  let env = {} as any
  const isBuild = command === 'build'
  if (!isBuild) {
    env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root)
  } else {
    env = loadEnv(mode, root)
  }
  return {
    base: env.VITE_BASE_PATH,
    plugins: [
      Vue({
        script: {
          defineModel: true
        }
      }),
      VueJsx(),
      ServerUrlCopy(),
      progress(),
      env.VITE_USE_ALL_ELEMENT_PLUS_STYLE === 'false'
        ? createStyleImportPlugin({
            resolves: [ElementPlusResolve()],
            libs: [
              {
                libraryName: 'element-plus',
                esModule: true,
                resolveStyle: (name) => {
                  if (name === 'click-outside') {
                    return ''
                  }
                  return `element-plus/es/components/${name.replace(/^el-/, '')}/style/css`
                }
              }
            ]
          })
        : undefined,
      VueI18nPlugin({
        runtimeOnly: true,
        compositionOnly: true,
        include: [resolve(__dirname, 'src/locales/**')]
      }),
      createSvgIconsPlugin({
        iconDirs: [pathResolve('src/assets/svgs')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: true
      }),
      PurgeIcons(),
      env.VITE_USE_MOCK === 'true'
        ? viteMockServe({
            ignore: /^\_/,
            mockPath: 'mock',
            localEnabled: !isBuild,
            prodEnabled: isBuild,
          })
        : undefined,
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      }),
      UnoCSS(),
      AutoImport({
        imports: ["vue", "@vueuse/core", "pinia", "vue-router"],
        resolvers: [
          ElementPlusResolver(),
        ],
        vueTemplate: true,
        dts: "src/types/auto-imports.d.ts",
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
        ],
        dirs: ["src/components", "src/**/components"],
        dts: "src/types/components.d.ts",
      }),
      createCopyJsonFilesPlugin(env, isBuild)
    ],

    css: {
      preprocessorOptions: {
        less: {
          additionalData: '@import "./src/styles/variables.module.less";',
          javascriptEnabled: true
        }
      }
    },
    postcss: {
      plugins: [
        pxtorem({
          rootValue: 192,
          minPixelValue: 2,
          propList: ["*"],
        }),
      ]
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js'
        },
        {
          find: /\@\//,
          replacement: `${pathResolve('src')}/`
        }
      ]
    },
    esbuild: {
      pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log'] : undefined,
      drop: env.VITE_DROP_DEBUGGER === 'true' ? ['debugger'] : undefined
    },
    build: {
      target: 'es2015',
      outDir: env.VITE_OUT_DIR || 'dist',
      sourcemap: env.VITE_SOURCEMAP === 'true',
      rollupOptions: {
        plugins: env.VITE_USE_BUNDLE_ANALYZER === 'true' ? [visualizer()] : undefined,
        output: {
          manualChunks: {
            'vue-chunks': ['vue', 'vue-router', 'pinia', 'vue-i18n'],
            'element-plus': ['element-plus'],
            'wang-editor': ['@wangeditor/editor', '@wangeditor/editor-for-vue'],
            echarts: ['echarts', 'echarts-wordcloud']
          }
        },
        external: [
          './src/utils/*.json',

        ]
      },
      cssCodeSplit: !(env.VITE_USE_CSS_SPLIT === 'false'),
      cssTarget: ['chrome31']
    },
    server: {
      host: "0.0.0.0",
      port: 5000,
      open: true,
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_APP_API_URL,
          changeOrigin: true,
        },
      },
    },
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'vue-types',
        'element-plus/es/locale/lang/zh-cn',
        'element-plus/es/locale/lang/en',
        '@iconify/iconify',
        '@vueuse/core',
        'axios',
        'qs',
        'echarts',
        'echarts-wordcloud',
        'qrcode',
        '@wangeditor/editor',
        '@wangeditor/editor-for-vue',
        'vue-json-pretty',
        '@zxcvbn-ts/core',
        'dayjs',
        'cropperjs'
      ]
    }
  }
}
